package com.cjc.hotel.server.handler;

import com.cjc.hotel.server.result.Result;
import com.cjc.hotel.server.result.ResultEnum;
import com.cjc.hotel.server.utils.ResultUtil;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author chenjuncai
 */
@ControllerAdvice
public class CommonExceptionHandler {

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result<Object> methodArgumentNotValidException(BindException e)
    {
        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        assert fieldError != null;
        return ResultUtil.defineFail(ResultEnum.INTERNAL_SERVER_ERROR.code,fieldError.getDefaultMessage());
    }
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<Object> exceptionHandler(Exception e)
    {
        return ResultUtil.defineFail(ResultEnum.INTERNAL_SERVER_ERROR.code,"服务器处理错误");
    }
    @ExceptionHandler(CommonException.class)
    @ResponseBody
    public Result<Object> commonException(CommonException e)
    {
        return ResultUtil.defineFail(ResultEnum.INTERNAL_SERVER_ERROR.code,e.getMessage());
    }
}
